package com.bos.web.action;

import com.bos.domian.base.WayBill;
import com.bos.service.WayBillSearchService;
import com.bos.utils.FileUtils;
import com.bos.web.BaseAction;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author misterWei
 * @create 2019年01月27号:21点40分
 * @mailbox mynameisweiyan@gmail.com
 */
@ParentPackage("json-default")
@Actions
@Namespace("/")
@Controller
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)//多例的
public class ExcelExportAction  extends BaseAction<WayBill>{
   @Autowired
   private WayBillSearchService wayBillSearchService;
    @Action(value = "wayBill_excelExport")
    public String wayBillExport(){
        //对当前有条件的数据进行导出Excel数据
        HSSFWorkbook hssfWorkbook = null;
        Pageable pageable = new PageRequest(0,1000);
        Map<String, Object> wayBillMap = wayBillSearchService.findAll(pageable, model);
        List<WayBill> waybillList = null;
        if (wayBillMap.get("waybillList") instanceof List) {
             waybillList = (List<WayBill>) wayBillMap.get("waybillList");
        }
        if (!waybillList.isEmpty()) {
            try {
            hssfWorkbook = new HSSFWorkbook();
            HSSFSheet sheet = hssfWorkbook.createSheet("运单数据");
            HSSFRow row = sheet.createRow(0);
            row.createCell(0).setCellValue("运单编号");
            row.createCell(1).setCellValue("产品类型");
            row.createCell(2).setCellValue("重量");
            row.createCell(3).setCellValue("原件数");
            row.createCell(4).setCellValue("配载要求");
            row.createCell(5).setCellValue("发货人地址");
            for (WayBill wayBill : waybillList) {
                HSSFRow DataRow = sheet.createRow(sheet.getFirstRowNum() + 1);
                DataRow.createCell(0).setCellValue(wayBill.getWayBillNum());
                DataRow.createCell(1).setCellValue(wayBill.getGoodsType());
                DataRow.createCell(2).setCellValue(wayBill.getWeight());
                DataRow.createCell(3).setCellValue(wayBill.getNum());
                DataRow.createCell(4).setCellValue(wayBill.getFloadreqr());
                DataRow.createCell(5).setCellValue(wayBill.getSendAddress());
            }
            //文件名编码设置
                String fileName = "BOS物流运单表数据.xls";
            //设置头信息
                fileName = FileUtils.encodeDownloadFilename(fileName, ServletActionContext.getRequest().getHeader("User-Agent"));
               //设置MIME类型
                ServletActionContext.getResponse().setContentType("application/vnd.ms-excel;charset=utf8");
               //设置文件格式以及名称
                ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;filename="+fileName);
                hssfWorkbook.write(ServletActionContext.getResponse().getOutputStream());
              }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if (hssfWorkbook != null) {
                        hssfWorkbook.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }else {

        }
       return NONE;
    }

    @Action(value = "wayBill_pfdExport")
    public void wayBillPdfExport(){
        Document document = null;
        Pageable pageable = new PageRequest(0,1000);
        Map<String, Object> wayBillMap = wayBillSearchService.findAll(pageable, model);
        List<WayBill> waybillList = null;
        if (wayBillMap.get("waybillList") instanceof List) {
            waybillList = (List<WayBill>) wayBillMap.get("waybillList");
        }
        try {
             document = new Document();
            //文件名编码设置
            String fileName = "BOS物流运单表数据.pdf";
            //设置头信息
            fileName = FileUtils.encodeDownloadFilename(fileName, ServletActionContext.getRequest().getHeader("User-Agent"));
            //设置MIME类型
            ServletActionContext.getResponse().setContentType("application/pdf;charset=utf8");
            //设置文件格式以及名称
            ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;filename="+fileName);
            PdfWriter.getInstance(document,ServletActionContext.getResponse().getOutputStream());
            document.open();  //必须先传入流再打开文档否则报错
            // 向document 生成pdf表格
            PdfPTable table = new PdfPTable(6);
            table.setWidthPercentage(100); // Width 100%
            table.setSpacingBefore(10f); // Space before table
            table.setSpacingAfter(10f); // Space after table
            // Set Column widths
            float[] columnWidths = { 1f, 1f, 1f ,1f, 1f, 1f}; //这里和上面6是一致的否则报错
            table.setWidths(columnWidths);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // 水平对齐方式
            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP); // 垂直对齐方式
            // 设置表格字体
            BaseFont cn = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
            //必须导入pdfAsianjar在可以否则不支持中文会报错的.
            Font font = new Font(cn, 8, Font.NORMAL, BaseColor.RED);
            // 向表格写数据
            // 表头
            table.addCell(buildCell("运单编号", font));
            table.addCell(buildCell("产品类型", font));
            table.addCell(buildCell("重量", font));
            table.addCell(buildCell("原件数", font));
            table.addCell(buildCell("配载要求", font));
            table.addCell(buildCell("发货人地址", font));
            for (WayBill wayBill : waybillList) {
                table.addCell(buildCell(wayBill.getWayBillNum() !=null?wayBill.getWayBillNum():"暂无数据" , font));
                table.addCell(buildCell(wayBill.getGoodsType()!=null?wayBill.getGoodsType():"暂无数据", font));
                table.addCell(buildCell(wayBill.getWeight().toString()!=null?wayBill.getWeight().toString():"暂无数据", font));
                table.addCell(buildCell(wayBill.getNum().toString()!=null?wayBill.getNum().toString():"暂无数据", font));
                table.addCell(buildCell(wayBill.getFloadreqr()!=null?wayBill.getFloadreqr():"暂无数据", font));
                table.addCell(buildCell(wayBill.getSendAddress()!=null?wayBill.getSendAddress():"暂无数据", font));
            }
            document.add(table);
        }catch (Exception e){
            e.printStackTrace();
        }finally {

            if (document != null) {
                document.close();
            }
        }

    }

    private PdfPCell buildCell(String content, Font font) {
        Phrase phrase = new Phrase(content, font);
        return new PdfPCell(phrase);
    }
}
